
// 内容脚本，用于在网页中执行任务
console.log('每日一键助手内容脚本已加载');

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'executeTask') {
    executeContentTask(request.task)
      .then(result => {
        sendResponse({ success: true, result });
      })
      .catch(error => {
        sendResponse({ success: false, error: error.message });
      });
    return true; // 保持消息通道开放
  }
});

// 在页面中执行任务
async function executeContentTask(task) {
  console.log('执行内容任务:', task);
  
  switch (task.type) {
    case 'fill-form':
      return fillForm(task.target, task.value);
    case 'click-element':
      return clickElement(task.target);
    case 'custom-script':
      return executeCustomScript(task.value);
    default:
      throw new Error(`不支持的任务类型: ${task.type}`);
  }
}

// 填写表单
function fillForm(selector, value) {
  const element = document.querySelector(selector);
  if (!element) {
    throw new Error(`找不到元素: ${selector}`);
  }
  
  element.focus();
  element.value = value;
  
  // 触发输入事件
  const inputEvent = new Event('input', { bubbles: true });
  const changeEvent = new Event('change', { bubbles: true });
  
  element.dispatchEvent(inputEvent);
  element.dispatchEvent(changeEvent);
  
  return `已填写 ${selector} 为 ${value}`;
}

// 点击元素
function clickElement(selector) {
  const element = document.querySelector(selector);
  if (!element) {
    throw new Error(`找不到元素: ${selector}`);
  }
  
  element.click();
  return `已点击 ${selector}`;
}

// 执行自定义脚本
function executeCustomScript(script) {
  try {
    const result = new Function(script)();
    return `自定义脚本执行完成: ${result}`;
  } catch (error) {
    throw new Error(`脚本执行失败: ${error.message}`);
  }
}

// 等待元素出现
function waitForElement(selector, timeout = 10000) {
  return new Promise((resolve, reject) => {
    const element = document.querySelector(selector);
    if (element) {
      resolve(element);
      return;
    }
    
    const observer = new MutationObserver(() => {
      const element = document.querySelector(selector);
      if (element) {
        observer.disconnect();
        resolve(element);
      }
    });
    
    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
    
    setTimeout(() => {
      observer.disconnect();
      reject(new Error(`等待元素超时: ${selector}`));
    }, timeout);
  });
}

// 等待页面加载完成
function waitForPageLoad() {
  return new Promise((resolve) => {
    if (document.readyState === 'complete') {
      resolve();
    } else {
      window.addEventListener('load', resolve);
    }
  });
}

// 辅助函数：获取元素文本
function getElementText(selector) {
  const element = document.querySelector(selector);
  return element ? element.textContent.trim() : null;
}

// 辅助函数：设置元素文本
function setElementText(selector, text) {
  const element = document.querySelector(selector);
  if (element) {
    element.textContent = text;
    return true;
  }
  return false;
}

// 辅助函数：等待指定时间
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// 导出函数供其他脚本使用
window.DailyHelper = {
  fillForm,
  clickElement,
  executeCustomScript,
  waitForElement,
  waitForPageLoad,
  getElementText,
  setElementText,
  sleep
};
